package com.car.slave.im.util;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Handler;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.car.slave.im.IMMessageManager;
import com.car.slave.im.model.user.IMUserMessage;

/**
 * 获取最近的消息.
 */
public class IMRecentMessage {
	
	private final Handler handler = new Handler();
	private RequestQueue queue;
	private Context contxt;
	
	public enum IMRecentMessageResult {
		NETWORK_ERROR,
		SERVER_ERROR
	}
	
	public interface IMRecentMessageCallback {
		public void begin();
		public void failed(IMRecentMessageResult result);
		public void recentMessages(List<IMUserMessage> messages);
	}
	
	private final IMRecentMessageCallback messageCallback;
	
	public IMRecentMessage(IMRecentMessageCallback messageCallback) {
		super();
		this.messageCallback = messageCallback;
	}

	/**
	 * 获取距message最近的count条信息.
	 * @param context
	 * @param message		为null的话，获取最新信息.
	 * @param count
	 */
	public void getRecentMessage(final Context context, final IMUserMessage message, final int count) {
		messageCallback.begin();
		
		// 先从本地获取
		final List<IMUserMessage> localMessages = IMMessageManager.shareInstance(context).getRecentMessages(context, count);
		if (localMessages.size() > 0) {
//		if (localMessages.size() == count) {
			messageCallback.recentMessages(localMessages);
			return;
		}

		// 如果本地聊天信息不够获取的数量，从网络获取
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					List<IMUserMessage> networkMessage = getNetworkMessage(message, count - localMessages.size());
					// 插入到数据库
					IMMessageManager.shareInstance(context).saveMessages(context, networkMessage);
					localMessages.addAll(networkMessage);
					handler.post(new Runnable() {
						@Override
						public void run() {
							messageCallback.recentMessages(localMessages);
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					
					handler.post(new Runnable() {
						@Override
						public void run() {
							// 获取网络消息失败
							messageCallback.failed(IMRecentMessageResult.NETWORK_ERROR);
						}
					});
				}
			}
		}).start();
	}
	
	// 获取网络的聊天信息.
	private List<IMUserMessage> getNetworkMessage(IMUserMessage message, int count) throws Exception {
		List<IMUserMessage> data = new ArrayList<IMUserMessage>();
		String url = "http://test.api.chezhil.com/message/history?user_id=user_id&timestamp=1440039226278&pagesize=20&user_id=1";
		StringRequest request = new StringRequest(url, new Listener<String>() {
			@Override
			public void onResponse(String response) {
				
			}
		}, new ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				
			}
		});
//		Volley.newRequestQueue(context).add(request);

		return data;
	}
}
